<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Jobs\DeleteStar;
use App\Models\Service;
use App\Models\Star;
use Dingo\Api\Http\Request;

class ServiceController extends BaseController
{

    public $model = Service::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');
        $service_merchant = $request->input('service_merchant');
        $category = $request->input('category');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $on_status = $request->input('on_status', -1);
        $is_special = $request->input('is_special', -1);
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');

        $list = Service::title($title)
            ->when($service_merchant, function ($q) use($service_merchant){
                $q->where('service_merchant', 'like', '%'.$service_merchant.'%');
            })
            ->when($is_special != -1, function ($q) use($is_special){
                $q->where('is_special', $is_special);
            })
            ->when($category, function ($q) use($category){
                if ($category == 1) {
                    $q->whereIn('category', [1, -1]);
                } else {
                    $q->where('category', $category);
                }
            })
            ->onStatus($on_status)
            ->startAt($start_at)
            ->endAt($end_at)
           ->orderBy($order_by_key, $order_by_value)->orderBy("id", "desc")
                ->paginate(\request('per_page', 20));

        return $this->paginate($list);
    }


    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $input = $request->input();
        $input['user_id'] = $this->getUserId();
        $id = \request("id");
        if ($id) {
            $model = Service::find($id);
            if (!$model) {
                return $this->failed("id对应数据不存在");
            }
            $model->update($input);
        } else {
            $info = Service::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);

        foreach ($arr_id as $id) {
            $model = $this->model::find($id);
            $model->delete();

            //删除收藏
            $this->dispatch(new DeleteStar(Star::TYPE_SERVICE, $id));
        }
        return $this->success([]);
    }


}

